# -*- coding: utf-8 -*-
import json

from flask import Blueprint, render_template, request, jsonify, make_response, current_app, redirect, url_for

from common.libs.UserSerivice import UserService
from web.models.user import User

route_user = Blueprint('user_page', __name__)


@route_user.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        "返回登录页面"
        return render_template("user/login.html")
    else:
        resp = {"code": 200, "msg": "登录成功", "data": {}}
        req = request.values
        login_name = req["login_name"] if "login_name" in req else ""
        login_pwd = req["login_pwd"] if "login_pwd" in req else ""  # 客户端密码：123456
        if (not login_name) or len(login_name) < 1:
            resp["code"] = -1
            resp["msg"] = "请输入正确的登录用户名"
            return jsonify(resp)
        if (not login_pwd) or len(login_pwd) < 1:
            resp["code"] = -1
            resp["msg"] = "请输入正确的密码"
            return jsonify(resp)

        # 验证用户名
        user_info = User.query.filter_by(login_name=login_name).first()
        if not user_info:  # 数据库查不到
            resp["code"] = -1
            resp["msg"] = "用户名不正确..."
            return jsonify(resp)

        # 验证密码
        salt = user_info.login_salt  # 密码的加盐值
        gen_pwd = UserService.genPwd(login_pwd, salt)  # gen_pwd：加密的密码
        print("md5加密加盐的16进制的值:32位十六进制",gen_pwd)
        if user_info.login_pwd != gen_pwd:
            resp["code"] = -1
            resp["msg"] = "密码不正确..."
            return jsonify(resp)
        #用户名和密码都正确：
        resp['data']['username'] = login_name
        resp['data']['password'] = login_pwd
        resp['data']['salt'] = salt
        # return jsonify(resp)
        # 登录成功后，要设置cookie , 但是jsonify函数没有设置cookie功能的
        # resp: {" code" : 200,"msg":"登录成功"，“data": "username" "hongfei " ,"password" :"123456}
        response = make_response(json.dumps(resp)) #将字典转为json字符串
        # 携带cookie
        cokie_str = UserService.genAuthCode(user_info) + "#" + str(user_info.uid)
        response.set_cookie(current_app.config.get("AUTH_COOKIE_NAME"), cokie_str,max_age=7*24*60*60) #current_app.config.get("AUTH_COOKIE_NAME"):food
        return response



@route_user.route("/edit")
def edit():
    return render_template("user/edit.html")


@route_user.route("/reset-pwd")
def resetPwd():
    return render_template("user/reset_pwd.html")

@route_user.route("/logout")
def logout():
    response = redirect(url_for('user_page.login'))
    response.delete_cookie(current_app.config['AUTH_COOKIE_NAME']) #删除cookie。AUTH_COOKIE_NAME:food
    return response

